/**
 * 
 */
package com.thon.controller.rest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.shiro.codec.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thon.commons.utils.ApplicationEnum.UserStatus;
import com.thon.commons.utils.ImageUtil;
import com.thon.controller.rest.dto.UserSettingsDTO;
import com.thon.controller.util.AttachmentUtil;
import com.thon.dao.util.Page;
import com.thon.entity.project.Preferential;
import com.thon.entity.project.Project;
import com.thon.entity.project.Region;
import com.thon.entity.user.Attachment;
import com.thon.entity.user.Charitarian;
import com.thon.entity.user.Institution;
import com.thon.entity.user.SendTo;
import com.thon.entity.user.User;
import com.thon.entity.user.UserBind;
import com.thon.entity.user.UserPushToken;
import com.thon.entity.user.UserSetting;
import com.thon.service.project.PreferentialService;
import com.thon.service.project.ProjectCommentService;
import com.thon.service.project.ProjectService;
import com.thon.service.project.RegionService;
import com.thon.service.user.AttachmentService;
import com.thon.service.user.CharitarianService;
import com.thon.service.user.CouponService;
import com.thon.service.user.InstitutionService;
import com.thon.service.user.LetterService;
import com.thon.service.user.MessageService;
import com.thon.service.user.PresentService;
import com.thon.service.user.SendToService;
import com.thon.service.user.UserBindService;
import com.thon.service.user.UserPushTokenService;
import com.thon.service.user.UserService;
import com.thon.service.user.UserSettingService;


/**
 * @file UserRestController.java
 * @author Zemo
 * @email zemochen@lanbaoo.com
 * @date 2013年12月9日 上午10:46:27
 * @description TODO
 */
@Controller
@RequestMapping("/api/user")
@SuppressWarnings({ "unchecked", "rawtypes" })
public class UserRestController {

	@Autowired
	private UserService userService;
	@Autowired
	private UserSettingService userSettingService;
	@Autowired
	private UserPushTokenService userPushTokenService;
	@Autowired
	private LetterService letterService;
	@Autowired
	private MessageService messageService;
	@Autowired
	private UserBindService userBindService;
	@Autowired
	private InstitutionService institutionService;
	@Autowired
	private CharitarianService charitarianService;
	@Autowired
	private ProjectService projectService;
	@Autowired
	private ProjectCommentService projectCommentService;
	@Autowired
	private AttachmentService attachmentService;
	@Autowired
	private CouponService couponService;
	@Autowired
	private SendToService sendToService;
	@Autowired
	private RegionService regionService;
	@Autowired
	private PresentService presentService;
	@Autowired
	private PreferentialService preferentialService;
	
	private static final Log log = LogFactory.getLog(UserRestController.class);

	// 根据用户id获取用户详情
	@RequestMapping(method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> getUserDetail(
			@RequestParam(value = "uid") int userId, Model model) {

		User user = userService.getUser(userId);
		Institution institution = institutionService
				.getInstitutionByUser(userId);
		Charitarian charitarian=charitarianService.getCharitarian(userId);

		model.addAttribute("user", user);
		model.addAttribute("institution", institution);
		model.addAttribute("charitarian", charitarian);
		return new ResponseEntity(model, HttpStatus.OK);
	}

	// 增加筛选功能
	@RequestMapping(value = "/fileterList", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listUsers(
			@RequestParam(value = "by", required = true) String by,
			@RequestParam(value = "condition", required = true) String condition,
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "10") int pageSize) {	
		
		Page<User> page = userService.listUserPage(by,condition,pageNo, pageSize);		

		return new ResponseEntity(page, HttpStatus.OK);
	}
	//根据用户角色获取用户列表
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> listFileterUsers(
			@RequestParam(value = "role", required = true) String role,		
			@RequestParam(value = "p", defaultValue = "1") int pageNo,
			@RequestParam(value = "s", defaultValue = "10") int pageSize) {

		log.debug("UserRestController query user list begin");

		Page<User> page = userService.findUserPage(role, pageNo, pageSize);

		log.debug("UserRestController query user list end");

		return new ResponseEntity(page, HttpStatus.OK);
	}
	
	// 根据用户id修改用户信息
	@RequestMapping(value = "/update/web", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updataWebUser(
			@Valid @RequestBody User user) {

		User oldUser = new User();
		oldUser = userService.getUser(user.getId());
		oldUser.setAvatar(user.getAvatar());		
		oldUser.setName(user.getName());		
		oldUser.setGender(user.getGender());
		oldUser.setAddress(user.getAddress());
		oldUser.setDescription(user.getDescription());
		oldUser.setEmail(user.getEmail());
		oldUser.setQq(user.getQq());
		oldUser.setWeiboUrl(user.getWeiboUrl());
		
		userService.updateUser(oldUser);
		return new ResponseEntity(oldUser, HttpStatus.OK);
	}

	// 移动端更新用户信息接口
	@RequestMapping(value = "/update", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updataUser(@Valid @RequestBody User user) {
		
		User oldUser = new User();
		oldUser = userService.getUser(user.getId());
		if(user.getAvatar()!=null&& user.getAvatar() != Integer.valueOf("-1"))
		{
			oldUser.setAvatar(user.getAvatar());
		}
		
		oldUser.setName(user.getName());
		oldUser.setGender(user.getGender());
		oldUser.setAddress(user.getAddress());
		oldUser.setDescription(user.getDescription());
		oldUser.setEmail(user.getEmail());
		oldUser.setQq(user.getQq());
		userService.updateUser(oldUser);
		return new ResponseEntity(oldUser, HttpStatus.OK);
	}

	// 根据用户id更新用户密码
	@RequestMapping(value = "/update/password", method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updatePassword(
			@RequestParam(value = "uid",required = true)int userId,
			@RequestParam(value = "newPassword",required = true)String newPassword,Model model) {
		System.out.println("uid:"+userId+",password:"+newPassword);
		User oldUser = userService.getUser(userId);
		oldUser.setPlainPassword(newPassword);	
		userService.resetPassword(oldUser);
		model.addAttribute("success", "reset password success");
		return new ResponseEntity(model, HttpStatus.OK);
		
	}

	//Ajax 验证用户密码
	@RequestMapping(value = "/check_password",method = RequestMethod.POST)
	@ResponseBody
	public String checkPassword(@RequestParam(value = "uid")int userId,
			@RequestParam(value = "oldPassword",required = true)String oldPassword){
		User oldUser = userService.getUser(userId);
		if (oldUser != null && oldUser.getPassword().equalsIgnoreCase(userService.entryptPassword(oldPassword, oldUser.getSalt()))) {
			return "true";
		} else {
			return"fail";
		}
	}
	/**
	 * 绑定登录平台
	 * @Title: bindAuth
	 * @Description: 绑定其他平台 platform:平台名称 1：iOS；2：Android；3：Web
	 *               bindType:绑定平台名称1：QQ；2：sina
	 * @param userBind
	 * @return 当已绑定过其他帐号返回状态码：208 绑定成功：201
	 */
	@RequestMapping(value = {"/bind","/web/bind"}, method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> bindAuth(
			@Valid @RequestBody UserBind userBind) {
		
		UserBind oldUserBind = userBindService.getUserBind(userBind.getUser().getId(), userBind.getBindType());
		if (oldUserBind == null) {
			userBindService.addUserBind(userBind);
			return new ResponseEntity(userBind, HttpStatus.CREATED);
		} else {
			return new ResponseEntity(oldUserBind, HttpStatus.ALREADY_REPORTED);
		}
	}
	
	@RequestMapping(value = "/get/bind/list",method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> getBindList(@RequestParam(value = "uid",required = true)Integer userId,Model model){
		
		List<UserBind> userBinds = userBindService.listUserBinds(userId);
		model.addAttribute("result", userBinds);
		return new ResponseEntity(model,HttpStatus.OK);
	}

	//取消绑定
	//@SuppressWarnings("unused")
	@RequestMapping(value = "/disbind",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> disBindAuth(
			@RequestBody UserBind userBind){
		Map map = new HashMap();
		log.debug("userbind"+userBind.toString());
		log.debug("user id:"+userBind.getUser().getId());
		log.debug("user bind type"+userBind.getBindType());
		UserBind oldUserBind = userBindService.getUserBind(userBind.getUser().getId(),userBind.getBindType());
		log.debug("olduser id:"+oldUserBind.getUser().getId());
		log.debug("olduser bind type"+oldUserBind.getBindType());
		if(oldUserBind != null){
			userBindService.deleteUserBind(oldUserBind.getId());
			map.put("success", "disbind successful");
			return new ResponseEntity(map,HttpStatus.OK);
		}else {
			map.put("error", "disbind fail");
			return new ResponseEntity(map,HttpStatus.BAD_REQUEST);
		}
	}
	
	//第一次绑定生成新用户
	@RequestMapping(value = "/bind/add_user",method = RequestMethod.POST)
	@ResponseBody
	public ResponseEntity<HttpEntity> addNewUser(@RequestBody User user){
		Map map = new HashMap();
		
		user.setStatus(UserStatus.open.getCode());
		//user.setRoles("user");
		user.setFund(0);
		userService.addUser(user);
		Attachment attachment = new Attachment();
		String imgUrl = user.getUrl();
		try {
			map = ImageUtil.readInputStream(imgUrl);
			byte[] fileData = (byte[]) map.get("data");
			String contentType = (String) map.get("contentType");
			String fileName = (String) map.get("fileName");
			attachment = AttachmentUtil.parse(fileData, contentType, fileName, fileData.length, user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		attachment.setUser(user);
		attachmentService.saveAttachment(attachment);
		AttachmentUtil.write(attachment,false);
		user.setAvatar(attachment.getId());
		userService.updateUser(user);
		
		String token = Base64.encodeToString((user.getLoginName()+":"+"").getBytes());
		map.put("token", token);
		map.put("user", user);
		return new ResponseEntity(map,HttpStatus.CREATED);
	}
	
	//更新用户设置
	@RequestMapping(value = "/update/setting",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> updateUserSetting(@RequestBody UserSettingsDTO userSettingsDTO){
		List<UserSetting> oldSettings = new ArrayList<UserSetting>();
		List<UserSetting> settings = userSettingsDTO.getUserSettings();
		oldSettings = userSettingService.getUserSetting(userSettingsDTO.getUserSettings().get(0).getUserId());
		if (oldSettings==null) {
			for (UserSetting userSetting : settings) {
				userSettingService.add(userSetting);
			}
		}else {
			for (UserSetting userSetting : settings) {
				int flag = 0;
				for (UserSetting oldUserSetting : oldSettings) {
					if(userSetting.getMetaKey().equals(oldUserSetting.getMetaKey())){
						flag++;
						oldUserSetting.setMetaValue(userSetting.getMetaValue());
						userSettingService.update(oldUserSetting);
						break;
					}
				}
				if(flag == 0){
					userSettingService.add(userSetting);
				}
			}
		}
		userSettingsDTO.setUserSettings(
				userSettingService.getUserSetting(
						userSettingsDTO.getUserSettings().get(0).getUserId()
						));
		return new ResponseEntity(userSettingsDTO,HttpStatus.OK);
	}
	
	//获取用户设置
	@RequestMapping(value = "/get/setting",method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> getUserSetting(
			@RequestParam(value="uid",required=true) int uid){
		UserSettingsDTO userSettingsDTO=new UserSettingsDTO();
		userSettingsDTO.setUserSettings(userSettingService.getUserSetting(uid));
				return new ResponseEntity(userSettingsDTO, HttpStatus.OK);		
	}
	//添加用户推送
	@RequestMapping(value="/push/token",method = RequestMethod.POST)
	public ResponseEntity<HttpEntity> userPushToken(@RequestBody UserPushToken userPushToken){
		
		userPushTokenService.addPushToken(userPushToken);
		return new ResponseEntity(HttpStatus.CREATED);
	}
	// 通过userId 获取部分数据数量
	@RequestMapping(value = "/count", method = RequestMethod.GET)
	public ResponseEntity<HttpEntity> count(
			@RequestParam(value = "uid", required = true) int userId,
			@RequestParam(value="status",defaultValue = "-1")int status,
			Model model) {

		Institution institution = new Institution();
		institution = institutionService.getInstitutionByUser(userId);
		if (institution != null) {
			Integer institutionId = institution.getId();
			List<Project> projects = projectService.listProjectsByStatus(institutionId,status);			
			Long startProjectCount = projectService.countProjectByStatus(institutionId,status);
 
			Integer unreadCommentCount = 0;
			Integer sum=0;
			model.addAttribute("startProjectCount", startProjectCount);
			for (Project project : projects) {
				sum = projectCommentService.countCommentToUser(
						0, project.getId(), 0,userId).intValue();
				unreadCommentCount += sum;
			}
			model.addAttribute("unreadCommentCount", unreadCommentCount);
		} else {
			Integer startProjectCount = 0;
			model.addAttribute("startProjectCount", startProjectCount);

			Integer unreadCommentCount = projectCommentService
					.countCommentToUser(0, 0, 0,userId).intValue();
			model.addAttribute("unreadCommentCount", unreadCommentCount);
		}

		List<Preferential> preferentialList =preferentialService.listPreferentialsBy();
		int sum=0;
		if(preferentialList!=null)
		{
			
			for(Preferential preferential:preferentialList)
			{
				Integer unreadCommentCount = projectCommentService
						.countCommentToUser(0, 0, preferential.getId(),userId).intValue();
				sum+= unreadCommentCount;
			}
			
		}
		model.addAttribute("unreadPreferntialCommentCount", sum);
	
		
		
		Integer shareProjectCount = projectService.countProject(
				"ym_project_shares", userId).intValue();
		model.addAttribute("shareProjectCount", shareProjectCount);

		Integer supportProjectCount = projectService.countProject(
				"ym_project_supports", userId).intValue();
		model.addAttribute("supportProjectCount", supportProjectCount);

		Integer attentionProjectCount = projectService.countProject(
				"ym_project_attentions", userId).intValue();
		model.addAttribute("attentionProjectCount", attentionProjectCount);

		Integer recommendProjectCount = projectService.countProject(
				"ym_project_recommends", userId).intValue();
		model.addAttribute("recommendProjectCount", recommendProjectCount);

		Integer unreadLetterCount = letterService.countUnReadLetter(0, userId)
				.intValue();
		model.addAttribute("unreadLetterCount", unreadLetterCount);

		Integer unreadMessageCount = messageService.countUnreadMessage(userId)
				.intValue();
		model.addAttribute("unreadMessageCount", unreadMessageCount);
		
		Integer unusedcouponCount =  couponService.countUnusedCoupon(userId)
				.intValue();
		model.addAttribute("unusedCouponCount", unusedcouponCount);
		User olduser = userService.getUser(userId);
		if(olduser==null)
			model.addAttribute("unreadPresentCount", 0);
		else{
		Integer unreadPresentCount = presentService.countPresent(olduser.getLoginName()).intValue();
		model.addAttribute("unreadPresentCount", unreadPresentCount);
		}
		return new ResponseEntity(model, HttpStatus.OK);
	}
	
	//列出优惠券类型
	@RequestMapping(value = "/coupon/type", method = RequestMethod.GET)
	public ResponseEntity<?> listTypeOfCoupon() {
		List<Map<String, String>> mapList = new ArrayList();
		Map<String, String> map = Maps.newHashMap();
		Map<String, String> map1 = Maps.newHashMap();
		Map<String, String> map2 = Maps.newHashMap();
		map.put("label", "money");
		map.put("description", "现金券");
		map1.put("label", "goods");
		map1.put("description", "商品券");
		map2.put("label", "activity");
		map2.put("description", "活动券");
		mapList.add(map);
		mapList.add(map1);
		mapList.add(map2);
		return new ResponseEntity(mapList, HttpStatus.OK);
	}
	
	//根据用户列出发货地址(移动端)
	@RequestMapping(value = "/sendto/list", method = RequestMethod.GET)
	public ResponseEntity<?> listSendToByUser(@RequestParam(value = "uid", required = true)int uid,
											  @RequestParam(value = "p", defaultValue = "1") int pageNo,
											  @RequestParam(value = "s", defaultValue = "10") int pageSize) {
		Page<SendTo> page = new Page<SendTo>();
		page = sendToService.findAllSendToById(uid, pageNo, pageSize);	
		return new ResponseEntity(page, HttpStatus.OK);
	}
	//根据区域id获取地名(web端)
	@RequestMapping(value = "/region/get", method = RequestMethod.GET)
	public ResponseEntity<?> listSendToByUserId(@RequestParam(value = "rid", required = true)int id
											 ) {
		Region region = new Region();
		region = regionService.getRegionById(id);
		return new ResponseEntity(region, HttpStatus.OK);
	}
	//新建收货地址
	@RequestMapping(value = "sendto/add", method = RequestMethod.POST)
	public ResponseEntity<?> addSendTo(@Valid SendTo sendto) {
		SendTo to = new SendTo();
		if(sendto.getIsDefault()==0){
			to.setCityId(sendto.getCityId());
			to.setDistrictId(sendto.getDistrictId());
			to.setProvinceId(sendto.getProvinceId());
			to.setEndRegion(sendto.getEndRegion());
			to.setName(sendto.getName());
			to.setPhone(sendto.getPhone());
			to.setIsDefault(sendto.getIsDefault());
			User user = userService.getUser(sendto.getUser().getId());
			to.setUser(user);
			sendToService.save(to);
			int id = to.getId();
			return new ResponseEntity(id, HttpStatus.OK);
		}else if (sendto.getIsDefault()==1) {
			List<SendTo> list = sendToService.listSendTos(sendto.getUser().getId());
			if(list.size()==0){
				to.setCityId(sendto.getCityId());
				to.setDistrictId(sendto.getDistrictId());
				to.setProvinceId(sendto.getProvinceId());
				to.setEndRegion(sendto.getEndRegion());
				to.setName(sendto.getName());
				to.setPhone(sendto.getPhone());
				to.setIsDefault(sendto.getIsDefault());
				User user = userService.getUser(sendto.getUser().getId());
				to.setUser(user);
				sendToService.save(to);
				int id = to.getId();
				return new ResponseEntity(id, HttpStatus.OK);
			}else{
				for (int i = 0; i < list.size(); i++) {
					SendTo e = new SendTo();
					e = list.get(i);
					e.setIsDefault(0);
					sendToService.update(e);
				}
				to.setCityId(sendto.getCityId());
				to.setDistrictId(sendto.getDistrictId());
				to.setProvinceId(sendto.getProvinceId());
				to.setEndRegion(sendto.getEndRegion());
				to.setName(sendto.getName());
				to.setPhone(sendto.getPhone());
				to.setIsDefault(sendto.getIsDefault());
				User user = userService.getUser(sendto.getUser().getId());
				to.setUser(user);
				sendToService.save(to);
				int id = to.getId();
				return new ResponseEntity(id, HttpStatus.OK);
			}
			
		}else {
			return new ResponseEntity(false, HttpStatus.OK);
		}
	}
	
	//修改发货地址
	@RequestMapping(value = "sendto/update", method = RequestMethod.POST)
	public ResponseEntity<?> updateSendTo(@Valid SendTo sendto,
										  @RequestParam(value = "uid", required = true)int uid,
										  @RequestParam(value = "id",required = true)int id) {
		SendTo to = sendToService.getById(id);
		if(sendto.getIsDefault()==0){
			to.setCityId(sendto.getCityId());
			to.setDistrictId(sendto.getDistrictId());
			to.setProvinceId(sendto.getProvinceId());
			to.setEndRegion(sendto.getEndRegion());
			to.setName(sendto.getName());
			to.setPhone(sendto.getPhone());
			to.setUser(userService.getUser(uid));
			to.setIsDefault(sendto.getIsDefault());
			sendToService.save(to);
			return new ResponseEntity(true, HttpStatus.OK);
		}else if (sendto.getIsDefault()==1) {
			List<SendTo> list = Lists.newArrayList();
			list=sendToService.listSendTos(uid);
			for (int i = 0; i < list.size(); i++) {
				SendTo e = list.get(i);
				e.setIsDefault(0);
				sendToService.update(e);
			}
			to.setCityId(sendto.getCityId());
			to.setDistrictId(sendto.getDistrictId());
			to.setProvinceId(sendto.getProvinceId());
			to.setEndRegion(sendto.getEndRegion());
			to.setName(sendto.getName());
			to.setPhone(sendto.getPhone());
			to.setUser(userService.getUser(uid));
			to.setIsDefault(sendto.getIsDefault());
			sendToService.save(to);
			return new ResponseEntity(true, HttpStatus.OK);
		}else {
			return new ResponseEntity(false, HttpStatus.OK);
		}
	}
	//根据id获取sendto地址
	@RequestMapping(value="/sendto/get/address",method = RequestMethod.GET)
	public ResponseEntity<?> getSendto(@RequestParam(value="id") int id){
		SendTo sendTo = sendToService.getById(id);
		return new ResponseEntity(sendTo, HttpStatus.OK);
	}
	
	//删除发货地址
	@RequestMapping(value = "sendto/del", method = RequestMethod.GET)
	public ResponseEntity<?> delSendTo(@RequestParam(value = "id", required = true)int id) {
		
		sendToService.del(id);
		return new ResponseEntity(true, HttpStatus.OK);
	}
	
	//获取默认地址
	@RequestMapping(value = "sendto/get", method = RequestMethod.GET)
	public ResponseEntity<?> getSendTo(@RequestParam(value = "uid", required = true)int uid,
									   @RequestParam(defaultValue = "1") int isDefault) {
		
		List<SendTo> list = sendToService.listDefaultAddress(uid, isDefault);
		List<SendTo> list2 = sendToService.listDefaultAddress(uid, 0);
		if(list.size()==0){
			return new ResponseEntity(list2, HttpStatus.OK);
		}else {
			return new ResponseEntity(list, HttpStatus.OK);
		}
	}
}
